package com.zzk.lanouhn.myapplication1.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.AllViewsAdapter;
import com.zzk.lanouhn.myapplication1.modles.AllComments;
import com.zzk.lanouhn.myapplication1.modles.AllViewsList;
import com.zzk.lanouhn.myapplication1.modles.ListDetails;
import com.zzk.lanouhn.myapplication1.utils.HttpUtils;
import com.zzk.lanouhn.myapplication1.view.CancelCollectDialog;
import com.zzk.lanouhn.myapplication1.view.CollectDialog;
import com.zzk.lanouhn.myapplication1.view.ScrollRecyclerView;

import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 消息页面的二级页面
 * Created by lanouhn on 16/9/2.
 */
public class ArticlesListDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_title, tv_name, tv_counts, tv_comments, tv_name2, tv_time;
    private ImageView iv_icon, iv_pic, iv_back,iv_collect,iv_collected,iv_circle,iv_share;
    private LinearLayout ll_content;
    private String id;
    private ListDetails details;//文章实体类
    private AllViewsList allViewsList;//大家都在看实体类
    private AllComments commentsList;//评论实体类
    private ScrollRecyclerView recyclerView_allviews;
    private LinearLayout ll_comments;
    private AllViewsAdapter allViewsAdapter;
    private CollectDialog collectDialog;
    private CancelCollectDialog cancelCollectDialog;
    private EditText et_commment;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articlelistdetails);
        initView();
        initData();
        initEvent();
        getDataFromWeb();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iv_icon.setImageBitmap(null);
        iv_pic.setImageBitmap(null);
        iv_back.setImageBitmap(null);
        System.gc();
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title_list_details);
        iv_icon = (ImageView) findViewById(R.id.iv_icon_author_list);
        tv_name = (TextView) findViewById(R.id.tv_name_authors_list);
        tv_counts = (TextView) findViewById(R.id.tv_viewcounts_list_details);
        tv_comments = (TextView) findViewById(R.id.tv_comments_list_details);
        iv_pic = (ImageView) findViewById(R.id.iv_pic_author_list);
        tv_name2 = (TextView) findViewById(R.id.tv_name_author_list);
        tv_time = (TextView) findViewById(R.id.tv_time_list_details);
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        recyclerView_allviews = (ScrollRecyclerView) findViewById(R.id.recycler_allviews_details_list);
        ll_comments = (LinearLayout) findViewById(R.id.ll_comments_details_list);
        iv_back = (ImageView) findViewById(R.id.iv_back_articlelist_details);
        iv_collect= (ImageView) findViewById(R.id.iv_collect);
        iv_collected= (ImageView) findViewById(R.id.iv_collected);
        iv_circle= (ImageView) findViewById(R.id.iv_circle);
        et_commment= (EditText) findViewById(R.id.et_commment);
        iv_share= (ImageView) findViewById(R.id.iv_share_articlelist_details);
    }

    private void initData() {
        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("内容");
    }

    private void initEvent() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_icon.setOnClickListener(this);
        tv_name.setOnClickListener(this);
        iv_collect.setOnClickListener(this);
        iv_collected.setOnClickListener(this);
        iv_circle.setOnClickListener(this);
        iv_share.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.iv_icon_author_list:
            case R.id.tv_name_authors_list:
                Intent intent=new Intent(ArticlesListDetailsActivity.this,AuthorsActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("authorId",details.getData().getUser().getUser_id());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.iv_collect:
                iv_collected.setVisibility(View.VISIBLE);
                iv_collect.setVisibility(View.INVISIBLE);
                collectDialog=new CollectDialog(ArticlesListDetailsActivity.this);
                Window window1=collectDialog.getWindow();
                window1.setWindowAnimations(R.style.dialogWindowAnim);
                WindowManager.LayoutParams lp1 = window1.getAttributes();
                window1.setGravity(Gravity.CENTER);
                lp1.alpha=1;
                lp1.width=320;
                lp1.height=420;
                window1.setAttributes(lp1);
                collectDialog.show();
                final Timer t1 = new Timer();
                t1.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        collectDialog.dismiss();
                        t1.cancel();
                    }
                },1500);
                break;
            case R.id.iv_collected:
                iv_collect.setVisibility(View.VISIBLE);
                iv_collected.setVisibility(View.INVISIBLE);
                cancelCollectDialog=new CancelCollectDialog(ArticlesListDetailsActivity.this);
                Window window2=cancelCollectDialog.getWindow();
                window2.setWindowAnimations(R.style.dialogWindowAnim);
                WindowManager.LayoutParams lp2 = window2.getAttributes();
                window2.setGravity(Gravity.CENTER);
                lp2.alpha=1;
                lp2.width=300;
                lp2.height=400;
                window2.setAttributes(lp2);
                cancelCollectDialog.show();
                final Timer t2 = new Timer();
                t2.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        cancelCollectDialog.dismiss();
                        t2.cancel();
                    }
                },1500);
                break;
            case R.id.iv_circle:
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                et_commment.setText("");
                break;
            case R.id.iv_share_articlelist_details:
                showShare();
                break;
          default:

              break;
        }
    }

    private void getDataFromWeb() {
        String url = "http://open4.bantangapp.com/topic/newInfo?";
        String dataUrl = "app_id=com.jzyd.BanTang&client_id=bt_app_android" +
                "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                "&track_user_id=2573914" +
                "&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                "&track_deviceid=866479023806507" +
                "&track_device_info=x600&channel_name=leshi" +
                "&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2" +
                "&screensize=1080&v=18" +
                "&id=" + id +
                "&trace_id=&relate_pid=&statistics_uv=1&is_night=0";
        try {
            HttpUtils.doPostAsyn(url, dataUrl, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    details = gson.fromJson(result, ListDetails.class);
                    if (details.getData().getContent_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                    String allviewsUrl = "http://open4.bantangapp.com/topics/topic/relationRec?";
                    String allviewsdataUrl = "app_id=com.jzyd.BanTang" +
                            "&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                            "&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                            "&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi" +
                            "&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18" +
                            "&id=" + id;
                    try {
                        HttpUtils.doPostAsyn(allviewsUrl, allviewsdataUrl, new HttpUtils.CallBack() {
                            @Override
                            public void onRequestComplete(String result) {
                                Gson gson2 = new Gson();
                                allViewsList = gson2.fromJson(result, AllViewsList.class);
                                if (allViewsList.getData().getTopic().size() > 0) {
                                    handler.sendEmptyMessage(2);
                                } else {
                                    handler.sendEmptyMessage(0);
                                }
                                String commentsUrl = "http://open4.bantangapp.com/topics/comment/list?";
                                String commentsDataUrl = "app_id=com.jzyd.BanTang" +
                                        "&client_id=bt_app_android" +
                                        "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                                        "&track_user_id=2573914" +
                                        "&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                                        "&track_deviceid=866479023806507" +
                                        "&track_device_info=x600&channel_name=leshi" +
                                        "&app_installtime=1471853508&app_versions=5.8.6" +
                                        "&os_versions=5.0.2&screensize=1080&v=18" +
                                        "&page=0&pagesize=20&id=" + id;
                                try {
                                    HttpUtils.doPostAsyn(commentsUrl, commentsDataUrl, new HttpUtils.CallBack() {
                                        @Override
                                        public void onRequestComplete(String result) {
                                            Gson gson3 = new Gson();
                                            commentsList = gson3.fromJson(result, AllComments.class);
                                            if (commentsList.getData().size() > 0) {
                                                handler.sendEmptyMessage(3);
                                            } else {
                                                handler.sendEmptyMessage(0);
                                            }
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    break;
                case 1:

                    ListDetails.DataBean.UserBean userBean = details.getData().getUser();
                    tv_title.setText(details.getData().getTitle());
                    tv_name.setText(userBean.getNickname());
                    tv_counts.setText(details.getData().getViews());
                    String comments = details.getData().getComments();
                    tv_comments.setText(comments + " 评论");
                    Picasso.with(ArticlesListDetailsActivity.this).load(userBean.getAvatar()).into(iv_icon);
                    Picasso.with(ArticlesListDetailsActivity.this).load(userBean.getAvatar()).into(iv_pic);
                    tv_name2.setText(userBean.getNickname());
                    tv_time.setText("创建于 " + details.getData().getDatestr());
                    for ( int i = 0; i < details.getData().getContent_list().size(); i++) {
                        int type = details.getData().getContent_list().get(i).getType();
                        if (type == 1) {
                            ImageView iv_item_pic = new ImageView(ArticlesListDetailsActivity.this);
                            iv_item_pic.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 500));
                            iv_item_pic.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            Picasso.with(ArticlesListDetailsActivity.this)
                                    .load(details.getData().getContent_list().get(i).getImage_url())
                                    .into(iv_item_pic);
                            ll_content.addView(iv_item_pic);
                        }
                        if (type == 2) {
                            TextView tv_content = new TextView(ArticlesListDetailsActivity.this);
                            tv_content.setText(details.getData().getContent_list().get(i).getText_content());
                            tv_content.setLineSpacing(1, 2);
                            tv_content.setGravity(View.TEXT_ALIGNMENT_CENTER);
                            ll_content.addView(tv_content);
                        }
                        if (type == 5) {
                            View view = LayoutInflater.from(ArticlesListDetailsActivity.this).inflate(R.layout.item_list_details, null);
                            RelativeLayout rl= (RelativeLayout) view.findViewById(R.id.rl_to_single_shop);
                            RelativeLayout rel_buy= (RelativeLayout) view.findViewById(R.id.rel_buy);
                            ImageView item_pic = (ImageView) view.findViewById(R.id.iv_item_pic_details);
                            TextView item_name = (TextView) view.findViewById(R.id.tv_item_name_details);
                            TextView item_price = (TextView) view.findViewById(R.id.tv_item_price_details);
                            TextView item_likes = (TextView) view.findViewById(R.id.tv_like_counts_details);
                            Picasso.with(ArticlesListDetailsActivity.this)
                                    .load(details.getData().getContent_list()
                                            .get(i)
                                            .getPic()).into(item_pic);
                            item_name.setText(details.getData().getContent_list().get(i).getItem_subtitle() +
                                    " " + details.getData().getContent_list().get(i).getItem_name());
                            item_price.setText("￥" + details.getData().getContent_list().get(i).getPrice());
                            item_likes.setText(details.getData().getContent_list().get(i).getLikes());

                            final int pos=i;

                            rl.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent=new Intent(ArticlesListDetailsActivity.this,SingleShopDetailsActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putString("singleId",details.getData().getContent_list().get(pos).getProduct_id());
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            });
                            rel_buy.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent=new Intent(ArticlesListDetailsActivity.this,MessageArticleGuide.class);
                                    intent.putExtra("guideUrl",details.getData().getContent_list().get(pos).getUrl());
                                    startActivity(intent);
                                }
                            });
                            ll_content.addView(view);
                        }
                    }
                    break;
                case 2:
                    allViewsAdapter = new AllViewsAdapter(ArticlesListDetailsActivity.this, allViewsList);
                    recyclerView_allviews.setAdapter(allViewsAdapter);
                    LinearLayoutManager mnger = new LinearLayoutManager(ArticlesListDetailsActivity.this);
                    mnger.setOrientation(LinearLayoutManager.VERTICAL);
                    recyclerView_allviews.setLayoutManager(mnger);
                    break;
                case 3:

                    String authorname = details.getData().getUser().getNickname();
                    if (commentsList.getData() != null) {

                        for (int i = 0; i < commentsList.getData().size(); i++) {
                            View view = LayoutInflater.from(ArticlesListDetailsActivity.this).inflate(R.layout.item_comments_details, null);
                            ImageView iv_icon_users = (ImageView) view.findViewById(R.id.iv_icon_comments);
                            TextView tv_content_comments = (TextView) view.findViewById(R.id.tv_contents_comments);
                            TextView tv_name_users = (TextView) view.findViewById(R.id.tv_name_users);
                            TextView tv_time = (TextView) view.findViewById(R.id.tv_time_comments);
                            TextView tv_isAuthor = (TextView) view.findViewById(R.id.tv_isauthor);
                            Picasso.with(ArticlesListDetailsActivity.this).load(commentsList.getData().get(i).getUser().getAvatar()).into(iv_icon_users);

                            tv_name_users.setText(commentsList.getData().get(i).getUser().getNickname());
                            tv_time.setText(commentsList.getData().get(i).getDatestr());

                            if (null != (commentsList.getData().get(i).getAt_user().getNickname())) {
                                String content = "回复 @" + commentsList.getData().get(i).getAt_user().getNickname() + ":" + commentsList.getData().get(i).getConent();
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
                                spannableStringBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.mycolor)), 2, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                tv_content_comments.setText(spannableStringBuilder);
                            } else {
                                tv_content_comments.setText(commentsList.getData().get(i).getConent());
                            }

                            String commentsname = commentsList.getData().get(i).getUser().getNickname();
                            if (authorname.equals(commentsname)) {
                                tv_isAuthor.setVisibility(View.VISIBLE);
                            } else {
                                tv_isAuthor.setVisibility(View.INVISIBLE);
                            }
                            ll_comments.addView(view);
                        }
                    }
                    break;
                default:

                    break;
            }
        }
    };
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }


}
